<template>
  <MenuPage 
    :columns="columns"
    :data="list"
    :page.sync="search.pageIndex"
    :size.sync="search.pageSize"
    :total="total"
    :loading="loading"
    @queryFun="getCaseAnalyseList">
    <template slot="search">
        <Button type="primary" ghost @click="showAddAndUpdate" class="md-add-jh"
          >创建{{ pageTitle }}</Button
        >
        <Divider type="vertical" />
        <div
          style="
            height: 32px;
            line-height: 32px;
            margin-left: 15px;
            flex-shrink: 0;
          "
        >
          <Checkbox v-model="creatByMeModal" @on-change="getCaseAnalyseList(1)"
            >由我创建</Checkbox
          >
        </div>
        <Input
          v-model.trim="search.name"
          clearable
          placeholder="案例名称"
          style="width: 180px; margin-left: 15px"
          @on-change="getCaseAnalyseList(1)"
        />
        <Button
          class="header-btn"
          type="primary"
          ghost
          style="height: 32px; margin-left: 5px"
          @click="refreshSurveyContentList()"
          ><i class="el-icon-refresh-right"
        /></Button>
    </template>
    <Modal
      v-model="modal.show"
      :title="`创建${pageTitle}`"
      :loading="modal.loading"
      @on-visible-change="createVisibleChange"
    >
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="96"
      >
        <FormItem label="案例名称" prop="name" key="name">
          <Input
            v-model.trim="formValidate.name"
            placeholder='名称不能包含下列任意英文字符 \ / : * ? " < > |,长度为1-40个字符'
          ></Input>
        </FormItem>
        <FormItem label="描述" prop="description" key="description">
          <Input
            v-model.trim="formValidate.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述信息"
          ></Input>
        </FormItem>
        <FormItem label="封面图片" prop="logo">
          <ItemUpload 
            ref="upload" 
            :filePath.sync="formValidate.iconPath"
            :format="['jpg', 'jpeg', 'png']"
            type="images"
          >
          </ItemUpload>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modal.show = false">取消</Button>
        <Button @click="saveCase" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="detailModal"
      :title="`${pageTitle}详情`"
      :mask-closable="false"
      :width="800"
      footer-hide
    >
      <div id="quesDetail">
        <p>
          <span class="label">案例名称</span><span>{{ currentItem.name }}</span>
        </p>
        <p>
          <span class="label">工程模板名称</span
          ><span>{{ currentItem.tmplName || "-" }}</span>
        </p>
        <p>
          <span class="label">绑定文档</span
          ><span>{{ currentItem.document || "-" }}</span>
        </p>
        <p>
          <span class="label">绑定视频</span
          ><span>{{ currentItem.video || "-" }}</span>
        </p>
        <p>
          <span class="label">绑定工具</span
          ><span>{{ currentItem.tool || "-" }}</span>
        </p>
        <p>
          <span class="label">创建者</span
          ><span>{{ currentItem.creatorName }}</span>
        </p>
        <p>
          <span class="label">创建时间</span
          ><span>{{ currentItem.createTime }}</span>
        </p>
        <p>
          <span class="label">单位</span
          ><span>{{ currentItem.companyName }}</span>
        </p>
        <p>
          <span class="label">描述</span
          ><span>{{ currentItem.description }}</span>
        </p>
      </div>
    </Modal>
  
</MenuPage>
</template>

<script>
import encryption from '@/libs/encryption.js';
import {
  getCaseAnalyseList,
  createCaseAnalyse,
  deleteCaseAnalyse,
  getCaseAnalyseDetail,
  changeCasePublishStatus
} from '@/api/event';
import { getstatusbyprjid } from '@/api/drill';
import { createTemplate } from '@/api/proTemplate';
import { validateName,validateName128 } from '@/libs/reg';
import pageTitle from '@/mixin/pageTitle';
import ItemUpload from '@/components/item-upload/single';
export default {
  mixins: [pageTitle],
  components: {
    ItemUpload
  },
  data() {
    return {
      currentItem: {},
      detailModal: false,
      showTip: false,
      uploaderror: false,
      uploadAction: '/api/minio/upload/permanent?visibility=company&type=images&bucket=images',
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      modal: {
        show: false,
        title: '',
        isAdd: true,
        loading: false
      },
      formValidate: {
        name: '',
        iconPath: '',
        description: ''
      },
      ruleValidate: {
        name: [
          { required: true, max: 40, message: '案例名称长度为1-40个字符', trigger: 'blur, change' },
          { validator: validateName, trigger: 'blur, change' }
        ]
      },
      creatByMeModal: false,
      USER_ID: '',
      search: {
        name: '',
        pageIndex: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      loading:true,
      columns: [
        {
          type:'link',
          placement: 'top-left',
          title: '案例名称',
          key: 'name',
          align: 'center',
          tooltip: true,
          width: 320,
          on: {
            click: (data) => {
              this.getCaseStatistics(data.id);
            }
          }
        },
        {
          title: '发布',
          key: 'checkStatus',
          render: (h, { row: { checkStatus } }) => {
            return h(
              'Tag',
              {
                props: {
                  type: 'border',
                  color: checkStatus ? 'var(--status-yes)' : 'var(--status-no)'
                }
              },
              checkStatus ? '是' : '否'
            );
          }
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          width: 350,
          tooltip: true
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          width: 150,
          tooltip: true
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center',
          width: 200,
          tooltip: true
        },
        {
          title: '操作',
          width: 240,
          key:'action',
          opList:[
            {
              txt:(data) => {
                return data.checkStatus ? '取消发布' : '发布'
              },
              title:(data) => {
                return `你确定要${data.checkStatus ? '取消发布' : '发布'}案例吗?`
              },
              disabled:(data) => {
                return this.setReBtnStatus(data) || !data.tmplId
              },
              on: {
                click: (data,e) => {
                  !(this.setReBtnStatus(data) || !data.tmplId) &&
                    this.changeCasePublishStatus(data);
                }
              },
              tooltip:true
            },
            {
              txt:'生成网络模板',
              title: '你确定要生成网络模板吗?',
              disabled:(data) => {
                return !data.projectId || this.setReBtnStatus(data)
              },
              on: {
                click: (data,e) => {
                  this.createNetworkTemplate(data.projectId, data.name);
                }
              },
              tooltip:true
            },
            {
                txt: '修改',
                disabled:this.setReBtnStatus,
                on: {
                  click: (data,e) => {
                    this.openCreatView(false, data);
                  }
                }
            },
            {
                txt: '删除',
                type: 'delete',
                tooltip: true,
                title: '你确定要删除吗?',
                disabled:this.setReBtnStatus,
                on: {
                  click: (data,e) => {
                    this.deleteCaseAnalyse(data.id);
                  }
                }
            },
          ]
        },
        {
          title: '操作',
          width: 410,
          show:false,
          //          fixed: 'right',
          placement: 'top-right',
          action: true,
          render: (h, params) => {
            return h(
              'div',
              {
                style: {
                  display: 'flex',
                  'align-items': 'center'
                }
              },
              [
                // h('ScriptData', {
                //     props: {
                //         disabled: !params.row.projectId || this.setReBtnStatus(params.row),
                //         projectId: params.row.projectId,
                //         size: 'small',
                //         btnType: 'text',
                //         iconSize: 26,
                //         hiddenBorder: true,
                //         iconColor: '#3D52C9',
                //         isButton: false
                //     },
                //     style: {
                //         width: '54px'
                //     }
                // }),
                h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      'ok-text': '确定',
                      'cancel-text': '取消',
                      type: 'error',
                      size: 'large',
                      title: `你确定要${params.row.checkStatus ? '取消发布' : '发布'}案例吗?`,
                      transfer: true
                    },
                    on: {
                      'on-ok': () => {
                        !(this.setReBtnStatus(params.row) || !params.row.tmplId) &&
                          this.changeCasePublishStatus(params.row);
                      }
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'text',
                          size: 'small',
                          disabled: this.setReBtnStatus(params.row) || !params.row.tmplId
                        },
                        attrs: {
                          title: params.row.checkStatus ? '取消发布' : '发布'
                        },
                        style: {
                          background: 'none',
                          border: 'none',
                          boxShadow: 'none'
                        }
                      },
                      [
                        h('img', {
                          attrs: {
                            src: this.setReBtnStatus(params.row)
                              ? require('../../assets/globalIcon/dis-publish.png')
                              : require('../../assets/globalIcon/publish.png')
                          },
                          style: {
                            cursor: 'pointer',
                            'margin-right': '5px',
                            'vertical-align': 'middle',
                            display: 'inline-block',
                            marginBottom: '4px'
                          }
                        })
                      ]
                    )
                  ]
                ),
                h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      'ok-text': '确定',
                      'cancel-text': '取消',
                      type: 'error',
                      size: 'large',
                      title: '你确定要生成网络模板吗?',
                      transfer: true
                    },
                    on: {
                      'on-ok': () => {
                        this.createNetworkTemplate(params.row.projectId, params.row.name);
                      }
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'text',
                          size: 'small',
                          disabled: !params.row.projectId || this.setReBtnStatus(params.row)
                        },
                        attrs: {
                          title: '生成网络模板'
                        },
                        style: {
                          border: 'none',
                          background: 'none',
                          boxShadow: 'none',
                          color:
                            !params.row.projectId || this.setReBtnStatus(params.row)
                              ? '#7D7F92'
                              : '#3D52C9'
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: 'md-cog',
                            size: 26
                          }
                        })
                      ]
                    )
                  ]
                ),
                h(
                  'Button',
                  {
                    attrs: {
                      title: '编辑'
                    },
                    props: {
                      type: 'text',
                      size: 'small',
                      disabled: this.setReBtnStatus(params.row)
                    },
                    style: {
                      background: 'none',
                      border: 'none',
                      boxShadow: 'none'
                    },
                    on: {
                      click: () => {
                        this.openCreatView(false, params.row);
                      }
                    }
                  },
                  [
                    h('img', {
                      attrs: {
                        src: !this.setReBtnStatus(params.row)
                          ? require('../../assets/project/modifys-h.png')
                          : require('../../assets/project/modifys.png')
                      },
                      style: {
                        cursor: 'pointer',
                        'margin-right': '5px',
                        'vertical-align': 'middle',
                        display: 'inline-block',
                        marginBottom: '4px'
                      }
                    })
                  ]
                ),
                h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      'ok-text': '确定',
                      'cancel-text': '取消',
                      type: 'error',
                      size: 'large',
                      title: '你确定要删除吗?',
                      transfer: true
                    },
                    on: {
                      'on-ok': () => {
                        this.deleteCaseAnalyse(params.row.id);
                      }
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'text',
                          size: 'small',
                          disabled: this.setReBtnStatus(params.row)
                        },
                        attrs: {
                          title: '删除'
                        },
                        style: {
                          border: 'none',
                          background: 'none',
                          boxShadow: 'none'
                        }
                      },
                      [
                        h('img', {
                          attrs: {
                            src: this.setReBtnStatus(params.row)
                              ? require('../../assets/project/delNote-d.png')
                              : require('../../assets/project/delNote-h.png')
                          },
                          style: {
                            cursor: 'pointer',
                            'margin-right': '5px',
                            'vertical-align': 'middle',
                            display: 'inline-block',
                            marginBottom: '4px'
                          }
                        })
                      ]
                    )
                  ]
                )
              ]
            );
          }
        }
      ]
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.userName = November.userName;
    this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
  },
  mounted() {
    let queryObj = sessionStorage.getItem('queryObj');
    if (queryObj) {
      let params = JSON.parse(queryObj);
      this.search.pageIndex = params.page || 1;
      this.search.name = params.name;
      this.creatByMeModal = params.designer == this.USER_ID ? true : false;
      sessionStorage.removeItem('queryObj');
    }
    this.getCaseAnalyseList();
    // this.setStyle();
    // window.addEventListener('resize', this.setStyle);
  },
  beforeDestroy() {
    clearTimeout(this.refreshTimer);
    window.removeEventListener('resize', this.setStyle);
  },
  methods: {
    // 查询案例详情
    getCaseStatistics(id) {
      getCaseAnalyseDetail(id)
        .then(({ code, message, data }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          let list = data.relations || [];
          let toolList = [],
            documentList = [],
            videoList = [];
          list.forEach((item) => {
            if (item.type === 1) {
              toolList.push(item.fileName);
            } else if (item.type === 2) {
              documentList.push(item.fileName);
            } else {
              videoList.push(item.fileName);
            }
          });
          this.currentItem = Object.assign(data, {
            document: documentList.join(', '),
            tool: toolList.join(', '),
            video: videoList.join(', ')
          });
          this.detailModal = true;
        })
        .catch(() => {
          this.$Message.error('获取案例详情异常');
        });
    },
    // 通过屏幕可显示高度，计算能展示多少条记录，最少需要展示一条
    setStyle() {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = setTimeout(() => {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        this.fullHeight = window.fullHeight;
        this.fullWidth = window.fullWidth;
        this.setTableHei = this.fullHeight - 197;
        this.search.pageSize = Math.floor(this.setTableHei / 96) || 1;
        this.getCaseAnalyseList();
      }, 200);
    },
    deleteCaseAnalyse(id) {
      deleteCaseAnalyse(id)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.$Message.success('删除成功');
          this.search.pageIndex =
            this.list.length === 1 && this.search.pageIndex > 1
              ? this.search.pageIndex - 1
              : this.search.pageIndex;
          this.getCaseAnalyseList();
        })
        .catch(() => {
          this.$Message.error('删除案例复盘异常');
        });
    },
    saveCase() {
      this.$refs.formValidate.validate((valid) => {
        if (!valid) {
          this.$Message.error('表单输入有误，请查看页面信息后重新输入!');
          this.cancelLoading(this.sceneModal);
          return;
        }
        createCaseAnalyse(this.formValidate)
          .then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            this.$Message.success('创建成功');
            this.getCaseAnalyseList();
            this.modal.show = false;
          })
          .catch(() => {
            this.$Message.error('创建案例复盘异常');
          });
      });
    },
    // 取消loading状态
    cancelLoading(modal) {
      modal.loading = false;
      setTimeout(() => {
        modal.loading = true;
      });
    },
    // 创建、编辑竞赛、演练的模态框打开时，重置表单，清空校验信息
    createVisibleChange(type) {
      if (type) {
        this.$refs.formValidate.resetFields();
        this.showTip = false;
      }
    },
    showAddAndUpdate() {
      this.formValidate = {
        name: '',
        iconPath: '',
        description: ''
      };
      this.modal.show = true;
    },
    // 创建网络模板
    createNetworkTemplate(projectId, name) {
      getstatusbyprjid(projectId).then(({ code, message, attribute = {} }) => {
        if (code !== 1) {
          this.$Message.warning(message);
          return;
        }
        let networkId = attribute.network && attribute.network.id;
        if (!networkId) {
          this.$Message.warning('未查询到网络');
          return;
        }
        createTemplate({
          name, // 使用案例名称作为网络模板的名称
          description: '',
          projectId: networkId, // 使用网络ID创建网络模板
          visibility: 'share'
        })
          .then(({ data = {} }) => {
            let { code, message } = data;
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            this.$Message.success('生成网络模板成功');
          })
          .catch(() => {
            this.$Message.error('生成网络模板异常');
          });
      });
    },
    // 打开创建、编辑页面
    openCreatView(isAdd, item) {
      sessionStorage.setItem(
        'queryObj',
        JSON.stringify({
          page: this.search.pageIndex,
          name: this.search.name,
          designer: this.creatByMeModal ? this.USER_ID : ''
        })
      );
      if (isAdd) {
        this.$router.push({
          name: 'creatCaseAnalyse',
          query: {
            page: this.search.pageIndex,
            action: 'create'
          }
        });
      } else {
        this.$router.push({
          name: 'creatCaseAnalyse',
          query: {
            page: this.search.pageIndex,
            action: 'update',
            id: item.id
          }
        });
      }
    },
    //查询案例列表
    getCaseAnalyseList(pageIndex) {
      if (pageIndex) {
        this.search.pageIndex = pageIndex;
      }
      this.search.creator = this.creatByMeModal ? this.USER_ID : undefined;
      getCaseAnalyseList(this.search)
        .then((res) => {
          if (res.code == 1) {
            this.list = res.data.items;
            this.total = res.data.total;
          } else {
            this.$Message.warning(res.message);
          }
          this.loading = false;
        })
        .catch(() => {
          this.$Message.error('获取数据列表异常');
          this.loading = false;
        });
    },
    //刷新按钮
    refreshSurveyContentList() {
      this.search.name = '';
      this.creatByMeModal = false;
      this.getCaseAnalyseList(1);
    },
    changePage(val) {
      this.loading = true;
      this.search.pageIndex = val;
      this.getCaseAnalyseList();
    },
    //按钮权限
    setReBtnStatus(params) {
      let userid = params.creator;
      let dis = userid != this.USER_ID;
      return dis;
    },
    // 发布/取消发布
    changeCasePublishStatus(caseInfo) {
      let { id, checkStatus } = caseInfo;
      let status = checkStatus === 0 ? 1 : 0;
      let txt = checkStatus === 0 ? '发布' : '取消发布';
      changeCasePublishStatus(id, status)
        .then(({ code, data, message }) => {
          if (code === 1) {
            caseInfo.checkStatus = status;
            this.$Message.success(`${txt}成功`);
          } else {
            this.$Message.error(`${txt}失败`);
          }
        })
        .catch((error) => {
          this.$Message.error(`${txt}失败`);
          console.log(error);
        });
    }
  }
};
</script>

<style scoped>
#quesDetail {
  display: table;
  width: 100%;
  border: 1px solid var(--table-border);
  table-layout: fixed;
  word-break: break-all;
}

#quesDetail p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}

#quesDetail p span {
  display: table-cell;
  border-bottom: 1px solid var(--table-border);
}
</style>
